package helpers;

import utilisateurs.modeles.ImagesGroup;
import utilisateurs.modeles.Image;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import servlets.LoadServlet;

/*
 * Cette classe permet de faciliter la récupération d'element d'un DOM
 */
public class DocumentHelper {
    
    private DocumentHelper() { }

    public static Element getElement(Element parent, String nom) {
        if (parent != null) {
            NodeList liste = parent.getElementsByTagName(nom);

            if (liste != null && liste.getLength() > 0) {
                return (Element) liste.item(0);
            }
        }

        return null;
    }

    public static String getValue(Element parent, String nom) {
        Element element = getElement(parent, nom);

        if (element != null && element.hasChildNodes()) {
            return element.getFirstChild().getNodeValue();
        }

        return null;
    }

    public static int getIntValue(Element parent, String nom) {
        return Integer.valueOf(getValue(parent, nom));
    }

    public static Image getImage(LoadServlet servlet, Element parent, String nom) {
        Element image = getElement(parent, nom);

        if (image != null) {
            String url = getValue(image, "URL");
            int width = getIntValue(image, "Width");
            int height = getIntValue(image, "Height");

            return servlet.getImageFacade().create(url, width, height);
        }

        return null;
    }

    public static ImagesGroup getImagesGroup(LoadServlet servlet, Element parent) {
        Image swatch = getImage(servlet, parent, "SwatchImage");
        Image small = getImage(servlet, parent, "SmallImage");
        Image medium = getImage(servlet, parent, "MediumImage");
        Image large = getImage(servlet, parent, "LargeImage");
        
        return servlet.getImagesGroupFacade().create(swatch, small, medium, large);
    }
}